import wx.grid as gridLib
import wx
from pydispatch import dispatcher

class MessagesTable(gridLib.PyGridTableBase):

    def __init__(self, pData):
        gridLib.PyGridTableBase.__init__(self)
        self.data = pData
        self.odd = gridLib.GridCellAttr()
        self.odd.SetBackgroundColour('sky blue')
        self.odd.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
        self.even = gridLib.GridCellAttr()
        self.even.SetBackgroundColour('sea green')
        self.even.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
        self.colLabels = ['displayId',
         'title',
         'filename',
         'size',
         'format',
         'tags',
         'download']
        self._rows = self.GetNumberRows()
        self._cols = self.GetNumberCols()



    def GetNumberRows(self):
        return len(self.data)



    def GetNumberCols(self):
        return 7



    def IsEmptyCell(self, row, col):
        return len(self.data) > row and self.data[row] is not None and self.data[row].get(self.GetColLabelValue(col)) is not None



    def GetValue(self, row, col):
        value = ''
        if self.data[row] != None:
            value = self.data[row].get(self.GetColLabelValue(col), '')
        if self.GetColLabelValue(col) == 'download' and value == '0':
            value = u'\u672a\u4e0b\u8f7d'
        elif self.GetColLabelValue(col) == 'download' and value == '1':
            value = u'\u5b8c\u6210'
        return value



    def GetColLabelValue(self, col):
        return self.colLabels[col]



    def SetValue(self, row, col, value):
        self.data[row][self.GetColLabelValue(col)] = value



    def ResetView(self, grid):
        """
      (Grid) -> Reset the grid view.   Call this to
      update the grid if rows and columns have been added or deleted
      """
        grid.BeginBatch()
        for (current, new, delmsg, addmsg,) in [(self._rows,
          self.GetNumberRows(),
          gridLib.GRIDTABLE_NOTIFY_ROWS_DELETED,
          gridLib.GRIDTABLE_NOTIFY_ROWS_APPENDED), (self._cols,
          self.GetNumberCols(),
          gridLib.GRIDTABLE_NOTIFY_COLS_DELETED,
          gridLib.GRIDTABLE_NOTIFY_COLS_APPENDED)]:
            if new < current:
                msg = gridLib.GridTableMessage(self, delmsg, new, current - new)
                grid.ProcessTableMessage(msg)
            elif new > current:
                msg = gridLib.GridTableMessage(self, addmsg, new - current)
                grid.ProcessTableMessage(msg)
                self.UpdateValues(grid)

        grid.EndBatch()
        self._rows = self.GetNumberRows()
        self._cols = self.GetNumberCols()
        for x in range(0, 7):
            grid.AutoSizeColumn(x, True)

        grid.AdjustScrollbars()
        grid.ForceRefresh()



    def UpdateValues(self, grid):
        """Update all displayed values"""
        msg = gridLib.GridTableMessage(self, gridLib.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
        grid.ProcessTableMessage(msg)



    def GetRowLabelValue(self, col):
        return ''




class CustTableGrid(wx.grid.Grid):

    def __init__(self, parent, id):
        wx.grid.Grid.__init__(self, parent, id)
        self._table = None
        self.SetRowLabelSize(0)
        self.SetMargins(0, 0)
        dispatcher.connect(self.onUpdateView, signal='MSG_FILE_DOWNLOADED')
        dispatcher.connect(self.onUpdateView, signal='MSG_ITEM_TAG_PARSED')
        dispatcher.connect(self.Reset, signal='MSG_RESET_GRID_VIEW')



    def onUpdateView(self):
        self._table.UpdateValues(self)
        self.AutoSizeColumn(5, True)



    def Reset(self):
        """reset the view based on the data in the table.  Call
      this when rows are added or destroyed"""
        self._table.ResetView(self)



    def SetTable(self, table, takeOwnership = False, selmode = gridLib.Grid.wxGridSelectCells):
        super(CustTableGrid, self).SetTable(table, takeOwnership, selmode)
        self._table = table




class View(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='Music Download Plus')
        categorys = ['classical',
         'country',
         'dance',
         'electronic',
         'fun',
         'jazz',
         'latin',
         'other',
         'pop',
         'rap-rnb-hiphop',
         'reggae',
         'rock',
         'themes',
         'voice']
        self.panel = wx.Panel(self)
        self.categoryLbl = wx.StaticText(self.panel, -1, 'Category:')
        self.category = wx.ComboBox(self.panel, -1, 'classical', (15, 30), wx.DefaultSize, categorys, wx.CB_DROPDOWN | wx.CB_READONLY)
        self.pageLbl = wx.StaticText(self.panel, -1, 'Page:')
        self.pageStart = wx.TextCtrl(self.panel, -1, '')
        self.splitLbl = wx.StaticText(self.panel, -1, '-')
        self.pageEnd = wx.TextCtrl(self.panel, -1, '')
        self.startIdLbl = wx.StaticText(self.panel, -1, 'Start ID:')
        self.startId = wx.TextCtrl(self.panel, -1, '')
        self.btStart = wx.Button(self.panel, -1, 'Start')
        self.btExport = wx.Button(self.panel, -1, 'Export')
        self.statusBar = wx.StatusBar(self.panel, -1)
        self.grid = CustTableGrid(self.panel, wx.ID_ANY)
        self.grid.SetMinSize(wx.Size(350, 300))
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        topSubSizer = wx.BoxSizer(wx.HORIZONTAL)
        topSubSizer.Add(self.categoryLbl, 0, wx.ALIGN_CENTER_VERTICAL)
        topSubSizer.Add(self.category, 0, wx.ALIGN_CENTER_VERTICAL)
        topSubSizer.Add(self.pageLbl, 0, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5)
        topSubSizer.Add(self.pageStart, 0, wx.ALIGN_CENTER_VERTICAL)
        topSubSizer.Add(self.splitLbl, 0, wx.ALIGN_CENTER_VERTICAL)
        topSubSizer.Add(self.pageEnd, 0, wx.ALIGN_CENTER_VERTICAL)
        topSubSizer.Add(self.startIdLbl, 0, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5)
        topSubSizer.Add(self.startId, 0, wx.ALIGN_CENTER_VERTICAL)
        topSubSizer.Add(self.btStart, 0, wx.ALIGN_CENTER_VERTICAL)
        mainSizer.Add(topSubSizer, 0, wx.EXPAND | wx.ALL, 5)
        mainSizer.Add(wx.StaticLine(self.panel), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 0)
        mainSizer.Add(self.grid, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.ALIGN_TOP)
        mainSizer.Add(wx.StaticLine(self.panel), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 0)
        mainSizer.Add(self.btExport, 0, wx.FIXED_MINSIZE | wx.ALIGN_RIGHT)
        mainSizer.Add(self.statusBar, 0, wx.EXPAND | wx.ALIGN_CENTER)
        self.panel.SetSizer(mainSizer)
        mainSizer.Fit(self)
        mainSizer.SetSizeHints(self)
        dispatcher.connect(self.onGuiStateChange, signal='MSG_STATE_CHANGE')



    def setContinueView(self):
        self.btStart.Enable()
        self.btStart.SetLabel('Continue')
        self.statusBar.SetStatusText('')



    def onGuiStateChange(self, msg):
        state = msg
        if state == 0:
            self.btStart.Enable()
            self.btStart.SetLabel('Start')
            self.statusBar.SetStatusText('')
        elif state == 1:
            self.btStart.Disable()
            self.statusBar.SetStatusText(u'\u9875\u9762\u89e3\u6790\u4e2d...')
        elif state == 2:
            self.statusBar.SetStatusText(u'\u9875\u9762\u89e3\u6790\u5b8c\u6210!')
        elif state == 3:
            self.btStart.Disable()
            self.statusBar.SetStatusText(u'\u97f3\u4e50\u6587\u4ef6\u4e0b\u8f7d\u4e2d...')
        elif state == 4:
            self.btStart.Enable()
            self.btStart.SetLabel('Continue')
            self.statusBar.SetStatusText(u'\u97f3\u4e50\u6587\u4ef6\u4e0b\u8f7d\u5b8c\u6210!')
        elif state == 5:
            self.btStart.Disable()
            self.statusBar.SetStatusText(u'Tag\u89e3\u6790\u4e2d...')
        elif state == 6:
            self.btStart.SetLabel('Start')
            self.btStart.Enable()
            self.statusBar.SetStatusText(u'\u5b8c\u6210')



    def showMessage(self, title, msgText):
        dlg = wx.MessageDialog(self, msgText, title, wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()




